<?php
namespace Template;
use Smarty\Exception;
use Smarty\Smarty;
use Yaf\View_Interface;

class SmartAdapter implements View_Interface
{
    public ?Smarty $smarty = null;

    /**
     * @param ?string $tmplPath
     * @param array|null $extraParams
     * @throws Exception
     */
    public function __construct(string $tmplPath = null, ?array $extraParams = array()) {
        $this->smarty = new Smarty();
        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }
        $this->smarty->setTemplateDir($extraParams['template_dir'] ?? null);
        $this->smarty->setCompileDir($extraParams['compile_dir'] ?? null);
        $this->smarty->setCacheDir($extraParams['cache_dir'] ?? null);
        $this->smarty->setCaching($extraParams['caching'] ?? false);
    }

    /**
     * 获取引擎
     * @return Smarty
     */
    public function getEngine(): Smarty
    {
        return $this->smarty;
    }

    /**
     * @param string|array $name
     * @param mixed $value
     * @return bool
     */
    function assign(string|array $name, mixed $value = NULL): bool
    {
        // TODO: Implement assign() method.
        $this->smarty->assign($name, $value);
        return true;
    }

    /**
     * @param $tpl
     * @param array|null $tpl_vars
     * @return bool
     * @throws Exception
     */
    function display($tpl, array $tpl_vars = null): bool
    {
        // TODO: Implement display() method.
        echo $this->smarty->fetch($tpl);
        return true;
    }

    /**
     * @param string $tpl
     * @param array|null $tpl_vars
     * @return string
     * @throws Exception
     */
    function render(string $tpl, array $tpl_vars = null): string
    {
        // TODO: Implement render() method.
        return $this->smarty->fetch($tpl);
    }

    /**
     * @param string $template_dir
     * @return void
     * @throws Exception
     */
    function setScriptPath(string $template_dir): void
    {
        // TODO: Implement setScriptPath() method.
        if (is_readable($template_dir)) {
            $this->smarty->setTemplateDir($template_dir);
            return;
        }
        throw new Exception('Invalid path provided');
    }

    /**
     * @return string
     */
    function getScriptPath(): string
    {
        // TODO: Implement getScriptPath() method.
        $template_dir = $this->smarty->getTemplateDir();
        if (is_array($template_dir)) {
            return $template_dir[0];
        }else {
            return $template_dir;
        }
    }

}
